package to_do

import (
	"context"
	"github.com/jinzhu/gorm"
)

const ModelKey = "Model5nXtkEK2"

//type ModelInterface interface {
//	SetDB(*gorm.DB)
//	Save() error
//}

func WithModel(ctx context.Context, m *Model) context.Context {

	return context.WithValue(ctx, ModelKey, m)
}

func (c *Context) GetModel(ctx context.Context) *Model {

	if m, ok := ctx.Value(ModelKey).(*Model); !ok {
		panic("get model error")
	} else {
		return m
	}
}

func NewModel(session *gorm.DB) *Model {
	return &Model{
		Session: session,
		m:       make(map[string]EntityInterface),
	}
}

type Model struct {
	Session *gorm.DB
	m       map[string]EntityInterface
}

func (m *Model) Get(key string) EntityInterface {
	return m.m[key]
}

func (m *Model) Set(key string, value EntityInterface) {
	m.m[key] = value
}

func (m *Model) Del(key string) {
	delete(m.m, key)
}

//func (m *Model) Save() error {
//
//	for _, v := range m.m {
//		if v.IsUpdate() {
//			if err := m.Session.Save(v).Error; err != nil {
//				return err
//			}
//		}
//	}
//	return nil
//}
